import React, { useState } from 'react';
import { View, StyleSheet, Text, TouchableOpacity, Modal, TextInput, Platform } from 'react-native';
import { ConversationList } from '../components/chat/ConversationList';
import { ChatScreen } from '../components/chat/ChatScreen';
import { useAppContext } from '../state/AppContext';
import { ImageViewer } from '../components/media/ImageViewer';
import theme from '../styles/theme';

export const MainScreen: React.FC = () => {
    const {
        state,
        dispatch,
        sendMessage,
        createNewConversation,
        selectConversation
    } = useAppContext();

    const [apiKeyModalVisible, setApiKeyModalVisible] = useState(!state.apiKey);
    const [apiKeyInput, setApiKeyInput] = useState(state.apiKey || '');
    const [imageViewerVisible, setImageViewerVisible] = useState(false);
    const [currentImageUrl, setCurrentImageUrl] = useState('');

    const handleApiKeySave = () => {
        dispatch({ type: 'SET_API_KEY', payload: apiKeyInput.trim() });
        setApiKeyModalVisible(false);

        // 如果没有会话，自动创建一个
        if (state.conversations.length === 0) {
            createNewConversation();
        }
    };

    const handleImagePress = (url: string) => {
        setCurrentImageUrl(url);
        setImageViewerVisible(true);
    };

    const handleSendMessage = async (input: any) => {
        await sendMessage(input);
    };

    const renderContent = () => {
        if (state.conversations.length === 0) {
            return (
                <View style={styles.emptyState}>
                    <Text style={styles.emptyStateTitle}>欢迎使用通义千问助手</Text>
                    <Text style={styles.emptyStateDescription}>开始一个新的对话</Text>
                    <TouchableOpacity
                        style={styles.emptyStateButton}
                        onPress={createNewConversation}
                    >
                        <Text style={styles.emptyStateButtonText}>创建对话</Text>
                    </TouchableOpacity>
                </View>
            );
        }

        if (!state.activeConversationId) {
            return (
                <View style={styles.emptyState}>
                    <Text style={styles.emptyStateTitle}>选择一个对话</Text>
                    <Text style={styles.emptyStateDescription}>或者创建一个新的对话</Text>
                    <TouchableOpacity
                        style={styles.emptyStateButton}
                        onPress={createNewConversation}
                    >
                        <Text style={styles.emptyStateButtonText}>创建对话</Text>
                    </TouchableOpacity>
                </View>
            );
        }

        return (
            <ChatScreen
                contextId={state.activeConversationId}
                onSendMessage={handleSendMessage}
                isProcessing={state.isLoading}
            />
        );
    };

    return (
        <View style={styles.container}>
            {/* API Key 设置弹窗 */}
            <Modal
                visible={apiKeyModalVisible}
                transparent={true}
                animationType="fade"
                onRequestClose={() => {
                    if (state.apiKey) {
                        setApiKeyModalVisible(false);
                    }
                }}
            >
                <View style={styles.modalContainer}>
                    <View style={styles.modalContent}>
                        <Text style={styles.modalTitle}>设置API密钥</Text>
                        <Text style={styles.modalDescription}>
                            请输入您的通义千问API密钥，以使用多模态功能
                        </Text>

                        <TextInput
                            style={styles.apiKeyInput}
                            value={apiKeyInput}
                            onChangeText={setApiKeyInput}
                            placeholder="输入API密钥..."
                            secureTextEntry={true}
                            autoCapitalize="none"
                            autoCorrect={false}
                        />

                        <View style={styles.modalButtonContainer}>
                            {state.apiKey && (
                                <TouchableOpacity
                                    style={styles.cancelButton}
                                    onPress={() => setApiKeyModalVisible(false)}
                                >
                                    <Text style={styles.cancelButtonText}>取消</Text>
                                </TouchableOpacity>
                            )}

                            <TouchableOpacity
                                style={styles.saveButton}
                                onPress={handleApiKeySave}
                                disabled={!apiKeyInput.trim()}
                            >
                                <Text style={styles.saveButtonText}>保存</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>

            {/* 图片查看器 */}
            <ImageViewer
                visible={imageViewerVisible}
                imageUrl={currentImageUrl}
                onClose={() => setImageViewerVisible(false)}
            />

            {/* 主界面 */}
            <View style={styles.header}>
                <Text style={styles.title}>通义千问助手</Text>

                <View style={styles.headerActions}>
                    <TouchableOpacity
                        style={styles.settingsButton}
                        onPress={() => setApiKeyModalVisible(true)}
                    >
                        <Text style={styles.settingsButtonText}>设置API密钥</Text>
                    </TouchableOpacity>
                </View>
            </View>

            <View style={styles.content}>
                <View style={styles.sidebar}>
                    <ConversationList
                        conversations={state.conversations}
                        selectedId={state.activeConversationId || undefined}
                        onSelectConversation={(conversation) => selectConversation(conversation.id)}
                        onNewConversation={createNewConversation}
                    />
                </View>

                <View style={styles.chatArea}>
                    {state.error && (
                        <View style={styles.errorContainer}>
                            <Text style={styles.errorText}>{state.error}</Text>
                            <TouchableOpacity
                                style={styles.dismissButton}
                                onPress={() => dispatch({ type: 'SET_ERROR', payload: null })}
                            >
                                <Text style={styles.dismissButtonText}>关闭</Text>
                            </TouchableOpacity>
                        </View>
                    )}

                    {renderContent()}
                </View>
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.background.default,
    },
    header: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: theme.spacing.md,
        borderBottomWidth: 1,
        borderBottomColor: theme.colors.divider,
        backgroundColor: theme.colors.primary.main,
    },
    title: {
        fontSize: theme.typography.fontSize.lg,
        fontWeight: theme.typography.fontWeight.bold,
        color: theme.colors.common.white,
    },
    headerActions: {
        flexDirection: 'row',
    },
    settingsButton: {
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.xs,
        borderRadius: theme.borderRadius.md,
        backgroundColor: 'rgba(255, 255, 255, 0.2)',
    },
    settingsButtonText: {
        color: theme.colors.common.white,
        fontSize: theme.typography.fontSize.sm,
    },
    content: {
        flex: 1,
        flexDirection: Platform.OS === 'web' ? 'row' : 'column',
    },
    sidebar: {
        width: Platform.OS === 'web' ? 300 : '100%',
        height: Platform.OS === 'web' ? '100%' : undefined,
        maxHeight: Platform.OS === 'web' ? undefined : '40%',
        borderRightWidth: Platform.OS === 'web' ? 1 : 0,
        borderRightColor: theme.colors.divider,
        borderBottomWidth: Platform.OS === 'web' ? 0 : 1,
        borderBottomColor: theme.colors.divider,
    },
    chatArea: {
        flex: 1,
    },
    emptyState: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        padding: theme.spacing.xl,
    },
    emptyStateTitle: {
        fontSize: theme.typography.fontSize.xl,
        fontWeight: theme.typography.fontWeight.bold,
        color: theme.colors.text.primary,
        marginBottom: theme.spacing.sm,
    },
    emptyStateDescription: {
        fontSize: theme.typography.fontSize.md,
        color: theme.colors.text.secondary,
        marginBottom: theme.spacing.lg,
        textAlign: 'center',
    },
    emptyStateButton: {
        backgroundColor: theme.colors.primary.main,
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.sm,
        borderRadius: theme.borderRadius.md,
    },
    emptyStateButtonText: {
        color: theme.colors.common.white,
        fontSize: theme.typography.fontSize.md,
        fontWeight: theme.typography.fontWeight.medium,
    },
    errorContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: theme.colors.error.light,
        padding: theme.spacing.sm,
        borderRadius: theme.borderRadius.sm,
        margin: theme.spacing.sm,
    },
    errorText: {
        flex: 1,
        color: theme.colors.error.main,
        fontSize: theme.typography.fontSize.sm,
    },
    dismissButton: {
        marginLeft: theme.spacing.sm,
        padding: theme.spacing.xs,
    },
    dismissButtonText: {
        color: theme.colors.error.dark,
        fontSize: theme.typography.fontSize.sm,
        fontWeight: theme.typography.fontWeight.medium,
    },
    modalContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalContent: {
        width: '90%',
        maxWidth: 500,
        backgroundColor: theme.colors.background.paper,
        borderRadius: theme.borderRadius.lg,
        padding: theme.spacing.lg,
    },
    modalTitle: {
        fontSize: theme.typography.fontSize.lg,
        fontWeight: theme.typography.fontWeight.bold,
        color: theme.colors.text.primary,
        marginBottom: theme.spacing.sm,
    },
    modalDescription: {
        fontSize: theme.typography.fontSize.md,
        color: theme.colors.text.secondary,
        marginBottom: theme.spacing.md,
    },
    apiKeyInput: {
        borderWidth: 1,
        borderColor: theme.colors.divider,
        borderRadius: theme.borderRadius.md,
        padding: theme.spacing.sm,
        fontSize: theme.typography.fontSize.md,
        color: theme.colors.text.primary,
        marginBottom: theme.spacing.md,
    },
    modalButtonContainer: {
        flexDirection: 'row',
        justifyContent: 'flex-end',
    },
    cancelButton: {
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.sm,
        marginRight: theme.spacing.sm,
    },
    cancelButtonText: {
        color: theme.colors.text.secondary,
        fontSize: theme.typography.fontSize.md,
        fontWeight: theme.typography.fontWeight.medium,
    },
    saveButton: {
        backgroundColor: theme.colors.primary.main,
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.sm,
        borderRadius: theme.borderRadius.md,
    },
    saveButtonText: {
        color: theme.colors.common.white,
        fontSize: theme.typography.fontSize.md,
        fontWeight: theme.typography.fontWeight.medium,
    }
}); 